<?php

namespace App\Http\Controllers;

use App\Models\Good;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function list(){
        $user = auth()->user();
        $map = [];
        // 订单状态
        $status = request('status');
        if ($status){
            $map[] = ['status','=',$status];
        }

        $list = $user->order()->where($map)->select(['id','order_no','name','mobile','address','goods_info','total_integral','status','created_at'])->simplePaginate(20)->transform(function ($item){
            $item->goods_info = json_decode($item->goods_info,true);
            return $item;
        });
        return renderSuccess($list);
    }

    public function detail(){
        $id = request('id');
        $order = auth()->user()->order()->select(['id','order_no','name','mobile','address','goods_info','total_integral','status','created_at'])->find($id);
        if (!$order){
            return renderError('订单不存在');
        }
        $order->goods_info = json_decode($order->goods_info,true);
        return renderSuccess($order);
    }

    // 收银台
    public function cashDesk(){
        $goods_ids = request('goods_ids');
        $address_id = request('address_id');
        $user = auth()->user();
        if (empty($address_id)){
            // 获取默认收货地址
            $address_id = $user->address()->where('user_address.default',1)->value('id');

            if (!$address_id){
                return renderError('请先添加收货地址');
            }
        }

        $address = $user->address()->select(['id','name','province','city','area','address','mobile','default'])->find($address_id);
        if (!$address){
            return renderError('收货地址不存在');
        }

        $goods_ids = explode(',',$goods_ids);
        // 获取购物车商品
        $shop_cart_goods = $user->shopcart()->select(['id','user_id','goods_id','quantity'])->with('goods:id,integral,cover,stock')->whereIn('goods_id',$goods_ids)->get();
        if ($shop_cart_goods->isEmpty()){
            return renderError('购物车商品不存在');
        }

        // 计算总价
        $total_integral = 0;
        foreach ($shop_cart_goods as $goods){
            $total_integral += $goods->goods->integral * $goods->quantity;
        }

        // 返回数据
        return renderSuccess([
            'address' => $address,
            'goods' => $shop_cart_goods,
            'total_integral' => $total_integral
        ]);
    }

    public function createOrder(){
        $goods_ids = request('goods_ids');
        $address_id = request('address_id');
        $user = auth()->user();
        if (empty($address_id)){
            // 获取默认收货地址
            $address_id = $user->address()->where('user_address.default',1)->value('id');

            if (!$address_id){
                return renderError('请先添加收货地址');
            }
        }
        $address = $user->address()->select(['id','name','province','city','area','address','mobile','default'])->find($address_id);

        if (!$address){
            return renderError('收货地址不存在');
        }

        $goods_ids = explode(',',$goods_ids);

        $shop_cart_goods = $user->shopcart()->select(['id','user_id','goods_id','quantity'])->with('goods:id,name,integral,cover,stock')->whereIn('goods_id',$goods_ids)->get();
        if ($shop_cart_goods->isEmpty()){
            return renderError('购物车商品不存在');
        }
        // 判断库存
        foreach ($shop_cart_goods as $goods){
            if ($goods->goods->stock < $goods->quantity){
                return renderError($goods->goods->name.'库存不足');
            }
        }

        // 计算总价
        $total_integral = 0;
        foreach ($shop_cart_goods as $goods){
            $total_integral += $goods->goods->integral * $goods->quantity;
        }

        // 判断积分是否足够
        if ($user->integral < $total_integral){
            return renderError('积分不足');
        }

        $goodslist = [];
        foreach ($shop_cart_goods as $goods) {
            $goodslist[] = [
                'goods_id' => $goods->id,
                'quantity' => $goods->quantity,
                'name' => $goods->goods->name,
                'integral' => $goods->goods->integral,
                'cover' => $goods->goods->cover,
            ];
        }

        DB::beginTransaction();
        // 创建订单
        $order_no = date('YmdHis').rand(1000,9999);
        $order = $user->order()->insert([
            'order_no' => $order_no,
            'user_id' => $user->id,
            'name' => $address->name,
            'mobile' => $address->mobile,
            'address' => $address->province.$address->city.$address->area.$address->address,
            'goods_info' => json_encode($goodslist,true),
            'total_integral' => $total_integral,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        if (!$order){
            DB::rollBack();
            return renderError('订单创建失败');
        }

        // 扣除积分
        integralLog($user->id, $total_integral, 0, '购买商品');

        // 成功交易 减少库存 销量增加 并且删除购物车
        foreach ($shop_cart_goods as $goods){
            $good = Good::find($goods->goods_id);
            $good->decrement('stock',$goods->quantity);
            $good->increment('sale',$goods->quantity);
            $goods->delete();
        }

        DB::commit();
        return renderSuccess([], '下单成功');
    }
}
